#pragma once
#include "Connection.hpp"
#include <sys/socket.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include "Log.hpp"
#include <cstring>
#include "HandlerConnection.hpp"

class Accepter
{
public:
    Accepter()
    {
    }

    void AccepterConnection(Connection *conn)
    {
        errno = 0;
        while (true)
        {
            struct sockaddr_in peer;
            socklen_t len = sizeof(peer);
            int sockfd = ::accept(conn->Sockfd(), (struct sockaddr *)&peer, &len);
            if (sockfd > 0)
            {
                lg.LogMessage(Info, "get a new link, sockfd is: %d\n", conn->Sockfd());
                SetNoBlock(sockfd);
                auto recver = std::bind(&HandlerConnection::Recver, std::placeholders::_1);
                auto sender = std::bind(&HandlerConnection::Sender, std::placeholders::_1);
                auto accepter = std::bind(&HandlerConnection::Accepter, std::placeholders::_1);

                // 将新连接放入到epoller中管理起来
                Connection *normal_conn = ConnectionFactory::BuildNormalConnection(sockfd,
                                                                                   recver, sender, accepter,
                                                                                   EPOLLIN | EPOLLET, conn->_R);
                conn->_R->AddConnnection(normal_conn);
            }
            else
            {
                if (errno == EAGAIN) // 读取到尾了，直接退出循环
                    break;
                else if (errno == EINTR)
                    continue;
                else
                {
                    lg.LogMessage(Warning, "get a error link\n");
                    break;
                }
            }
        }
    }

    ~Accepter()
    {
    }

private:
};